package core

import (
	"fmt"
	"github.com/dgrijalva/jwt-go"
)

// CreateToken 创建token
func CreateToken(secret string, val jwt.MapClaims) (string, error) {
	t := jwt.NewWithClaims(jwt.SigningMethodHS256, val)
	result, err := t.SignedString([]byte(secret))
	if err != nil {
		return "", err
	}
	return result, nil
}

// AnalysisToken 解析token
func AnalysisToken(secret, token string) (jwt.MapClaims, error) {
	t, err := jwt.Parse(token, func(token *jwt.Token) (interface{}, error) {
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
		}
		return []byte(secret), nil
	})

	if err != nil {
		return nil, err
	}

	if claims, ok := t.Claims.(jwt.MapClaims); ok && t.Valid {
		return claims, nil
	}
	return nil, fmt.Errorf("analysis token fail")
}
